/**
 * Created by xuxujunjunforever on 2015/12/1.
 */
'use strict'

let models = require('../models');
let config = require('../../config');
let errors = config.errors;
let Session = require('../middlewares/session');

let UserDao = models.UserDao;
let SchoolDao = models.SchoolDao;
let RoleDao = models.RoleDao;
let PrivilegeDao = models.PrivilegeDao;

let User = models.User;
let School = models.School;
let Privilege = models.Privilege;
let Role = models.Role;

let userService = require('../services/user');

let actionLogin = {
    handler(req, res) {
        let user = UserDao.findOne({
            name: req.query.name,
            password: req.query.password
        });

        if ( !user ) {
            throw config.errors.UsernamePasswordMismatched;
            return;
        }

        let token = Session.newToken(req, user);
        req.session.login = {
            user: user
        };
        let userInformation = makeUserInformation(user);

        res.cookie('token', token, {
            maxAge: config.params.user.token.expired * 60 * 1000
        });

        res.redirect('/user/dispatch');
    }
};

let actionLogout = {
    login: true,
    handler(req, res) {
        Session.removeToken(req, req.session.login.user);

        res.json({
            successful: true
        });
    }
};

let actionGetUserInfomation = {
    login: true,
    handler(req,res) {
        let userInformation = makeUserInformation(req.session.login.user);
        res.json({
            successful: true,
            data: {
                user: userInformation
            }
        });
    }
};

let actionCreateUser = {
    privileges:['manage_user'],
    fields:{
        user:{
            name: true,
            password: true,
            role: true,
            realName: true,
            telephone:true,
            school:{
                id:true
            },
            dormitory: true,
            status: true
        }
    },
    handler(req, res) {
        let user = new User(req.body.user);

        let role = RoleDao.findOne({
            id:user.role.id
        });
        if(role == null){
            throw config.errors.RoleCanNotFound;
            return;
        }

        let school = SchoolDao.findOne({
           id:user.school.id
        });
        if(school == null){
            throw config.errors.SchoolNotFound;
            return;
        }

        UserDao.create(user);

        let userInfomation = user.toObject({recursive:true});

        res.json({
            successful:true,
            data:{
                user:userInfomation
            }
        });
    }
};

let actionRefreshUser = {
    login:true,
    handler(req,res) {
        let user = req.body.user;

        let refreshUser = UserDao.findOne({
           id:user.id
        });
        if(refreshUser == null){
            throw config.errors.UserCanNotFound;
            return;
        }

        let userInfomation = refreshUser.toObject({recursive:true});

        res.json({
            successful:true,
            data:{
                user:userInfomation
            }
        });
    }
};

let actionUpdateUser = {
    login:true,
    handler(req,res) {
        let newuser = req.body.user;

        let olduser = UserDao.findOne({
           id:newuser.id
        });
        if(olduser == null){
            throw config.errors.UserCanNotFound;
            return;
        }

        let role = RoleDao.findOne({
            id:newuser.role.id
        });
        if(role == null){
            throw config.errors.RoleCanNotFound;
            return;
        }

        let school = SchoolDao.findOne({
            id:newuser.school.id
        });
        if(school == null){
            throw config.errors.SchoolNotFound;
            return;
        }

        UserDao.update(newuser);

        let userInfomation = newuser.toObject({recursive:true});

        res.json({
            successful:true,
            data:{
                user:newuser
            }
        });
    }
};

let actionRemoveUser = {
    privileges:['manage_user'],
    fields:{
        user:{
            id:true
        }
    },
    handler(req,res) {
        if ( !req.session.login ) {
            throw config.errors.UserNotLogin;
            return;
        }

        let user = UserDao.findOne({
           id:req.body.user.id
        });
        if(user == null){
            throw config.errors.UserCanNotFound;
            return;
        }

        UserDao.remove(user);

        res.json({
            successful:true
        });
    }
};

let actionUserAll = {
    privileges:['manage_user'],
    handler(req,res) {
        if ( !req.session.login ) {
            throw config.errors.UserNotLogin;
            return;
        }

        let users =  UserDao.find({});
        let userInfo = {
            includes: [
                'name',
                {
                    'role':[]
                },
                'realName',
                'telephone',
                {
                    'school':[]
                },
                'dormitory',
                'status'
            ]
        };

        let plainusers = User.toObjectArray(users,userInfo);
        res.json({
            successful:true,
            data:{
                users:plainusers
            }
        });
    }
};

let actionModifyPersonalUserInfo = {
    login:true,
    fields:{
        user:{
            name:true,
            school:{
                id:true
            }
        }
    },
    handler(req,res) {
        console.log(111);
        if ( !req.session.login ) {
            throw config.errors.UserNotLogin;
            return;
        }

        let user = UserDao.findOne({
            id:req.session.login.user.id
        });

        let school = SchoolDao.findOne({
           id:req.body.user.school.id
        });
        if(!school){
            throw  config.errors.SchoolNotFound;
            return;
        }

        user.name = req.body.user.name;
        user.realName = req.body.user.realName;
        user.telephone = req.body.user.telephone;
        user.school = school;
        user.dormitory = user.dormitory;

        UserDao.update(user);

        let plainuser = user.toObject({
            includes: [
                'name',
                {
                    'role':[]
                },
                'realName',
                'telephone',
                {
                    'school':[]
                },
                'dormitory',
                'status'
            ]
        });

        res.json({
            successful:true,
            data:{
                user:plainuser
            }
        });
    }
};

function makeUserInformation(user){
    user = UserDao.findOne({
       id:user.id
    });
    let userInformation = user.toObject({
        includes:[
            'name',
            'status',
            {
                role:[
                    'name',
                    {
                        "privileges": [
                            'name'
                        ]
                    }
                ]
            }
        ]
    });

    return userInformation;
}

module.exports = {
    actionLogin,
    actionLogout,
    actionGetUserInfomation,
    actionCreateUser,
    actionRefreshUser,
    actionRemoveUser,
    actionUserAll,
    actionModifyPersonalUserInfo
};
